import I18n from 'i18n-js';
import { action, toJS, makeAutoObservable } from 'mobx';
import { queryNoticesSetting, updateNoticesSetting, getCallNumberList, ICallPhoneNumber, IUserMessage } from '@/services/aepNotices';
import { addContact, editContact, getContactList, deleteContact } from '@/services/home';
import homeModel from './homes';
import { formattingNum, getWxDeviceSN } from '@/utils';
import Taro from '@tarojs/taro';
import { getItemForPk } from '@/config/product';
import { getWxModeId } from '@/services/messages';
import { getWechatTicket } from '@/services/aepDeviceApi';

export interface INoitEditParam {
  phoneMessageSwitch?: boolean;
  phoneSwitch?: boolean;
}

export interface IWxNotDisturbTime {
  wxBeginHour: number;
  wxBeginMinute: number;
  wxEndHour: number;
  wxEndMinute: number;
}

export interface ISettingEditParam extends Pick<IUserMessage,
  'wechatNotice' | 'wxDoNotDisturb' | 'wxBeginHour' | 'wxBeginMinute' | 'wxEndHour' | 'wxEndMinute' | 'deviceConfigSwitch'> {

}

export function checkWxDoNotDisturbTime({ wxBeginHour, wxBeginMinute, wxEndHour, wxEndMinute }: IWxNotDisturbTime) {
  return typeof wxBeginHour === "number"
    && typeof wxBeginMinute === "number"
    && typeof wxEndHour === "number"
    && typeof wxEndMinute === "number"
}

export function getDisturbTimeText(time?: IWxNotDisturbTime) {
  if (time && checkWxDoNotDisturbTime(time)) {
    return `${time.wxBeginHour}:${formattingNum(time.wxBeginMinute)}-${time.wxEndHour}:${formattingNum(time.wxEndMinute)}`;
  }
  return I18n.t('未设置')
}



class AlarmPush {

  concatList: IPeople[] = [];

  phoneMessageSwitch: boolean = false;

  phoneSwitch: boolean = false;

  wechatNotice: boolean = false;

  wxDoNotDisturb: boolean = false;

  wxDoNotDisturbTime: IWxNotDisturbTime | undefined = undefined;

  callNumberList: ICallPhoneNumber[] = [];

  setting: any;

  constructor() {
    makeAutoObservable(this);
  }

  async getAlarmSetting() {
    const data = await queryNoticesSetting();
    if (data.success) {
      const {
        callNotice, smsNotice, wechatNotice, wxDoNotDisturb,
        wxBeginHour, wxBeginMinute, wxEndHour, wxEndMinute
      } = data.data!;
      this.setting = { ...data.data };
      if (data.data && data.data.zone === null) {
        // 没有时区信息，先同步一次给服务器
        this.updateSettingToService();
      }
      this.phoneSwitch = callNotice;
      this.phoneMessageSwitch = smsNotice;
      this.wechatNotice = wechatNotice;
      this.wxDoNotDisturb = wxDoNotDisturb;
      // 都是number类型的话，才是有值，不然的话，代表没设置
      const time: IWxNotDisturbTime = { wxBeginHour, wxBeginMinute, wxEndHour, wxEndMinute };
      if (checkWxDoNotDisturbTime(time)) {
        this.wxDoNotDisturbTime = time;
      }
    }
  }

  async updateSettingToService() {
    await updateNoticesSetting({
      ...this.setting
    });
  }


  async getContacts() {
    const result = await getContactList(homeModel.current);
    if (result.success) {
      this.concatList = result.data;
    }
  }

  async getWhitePhoneNumberList() {
    const result = await getCallNumberList();
    if (result.success) {
      this.callNumberList = result.data!;
    }
  }

  async editOrAddContact(p: IPeople) {
    let res;
    const { areaCode, mobile, id, name } = p;
    if (id) {
      res = await editContact({ id, areaCode, mobile, name, homeId: homeModel.current });
    } else {
      res = await addContact({ areaCode, mobile, name, homeId: homeModel.current });
    }
    return res;
  }

  async delete(id: number) {
    return deleteContact([id]);
  }

  /**
   * 存在modeID 发起订阅
   * 否则跳过
   */
  async subscribesDeviceWXMessage(device: IDevice) {
    const productConfig = getItemForPk(device.productKey)
    if (device && !device.isVirtual && productConfig && productConfig.supportDeviceAlarm) {
      const modelId = await getWxModeId(productConfig.productKey);
      console.log("modelId", modelId)
      if (modelId) {
        // 有模板id才需要订阅
        const sn = getWxDeviceSN(device.mac);
        const res = await getWechatTicket({ modelId, mac: sn, productKey: device.productKey });
        console.log("ticket", res)
        if (res.success && res.data && res.data.snTicket.sn_ticket && res.data.templates) {
          const snTicket = res.data.snTicket.sn_ticket;
          const tmplIds = res.data.templates.split(',');
          Taro.requestSubscribeDeviceMessage({
            tmplIds,
            sn,
            snTicket,
            modelId,
            success(resData) {
              console.log("[wx.requestSubscribeDeviceMessage success]: ", resData);
            },
            fail(err) {
              console.log("[wx.requestSubscribeDeviceMessage fail]: ", err);
            },
          });
        }
      } else {
        console.log('subscribesDeviceWXMessage no config');
      }
    } else {
      console.log('subscribesDeviceWXMessage no productConfig');
    }
  }

  async editNotiSwitch({ phoneMessageSwitch, phoneSwitch }: INoitEditParam) {
    let param: any = {};
    if (phoneSwitch !== undefined) {
      this.phoneSwitch = phoneSwitch;
      param.callNotice = phoneSwitch;
      if (phoneSwitch) {
        param.deviceConfigSwitch = true;
      }
    }
    if (phoneMessageSwitch !== undefined) {
      this.phoneMessageSwitch = phoneMessageSwitch;
      param.smsNotice = phoneMessageSwitch;
      if (phoneMessageSwitch) {
        param.deviceConfigSwitch = true;
      }
    }
    const data = await updateNoticesSetting(param);
    console.log('data', data)
    return data;
  }

  async editWechatSetting({ wechatNotice, wxDoNotDisturb, wxBeginHour, wxEndHour, wxBeginMinute, wxEndMinute }: ISettingEditParam) {
    let param: ISettingEditParam = {}
    if (wechatNotice !== undefined) {
      this.wechatNotice = wechatNotice;
      param.wechatNotice = wechatNotice;
      if (wechatNotice) {
        param.deviceConfigSwitch = true;
      }
    }
    if (wxDoNotDisturb !== undefined) {
      this.wxDoNotDisturb = wxDoNotDisturb;
      param.wxDoNotDisturb = wxDoNotDisturb;
    }
    const time = { wxBeginHour, wxEndHour, wxBeginMinute, wxEndMinute };
    if (checkWxDoNotDisturbTime(time)) {
      this.wxDoNotDisturbTime = time;
      param = { ...param, ...time };
    }
    const data = await updateNoticesSetting(param);
    return data;
  }


  cleanData() {
    this.concatList = [];
  }
}

const AlarmPush_Store_Key = "alarmPush";

export { AlarmPush, AlarmPush_Store_Key };


export default new AlarmPush();
